//
//  HapkiFreestyleController.swift
//  I.S.A.P WT
//
//  Created by Илья Проскурнев on 24.05.2021.
//  Copyright © 2021 Илья Проскурнев. All rights reserved.
//

import UIKit

class HapkiFreestyleController : UIViewController, UINavigationControllerDelegate, RadioButtonFreestyle1Delegate, RadioButtonFreestyle2Delegate, RadioButtonFreestyle3Delegate, RadioButtonFreestyle4Delegate, RadioButtonFreestyle5Delegate, RadioButtonFreestyle6Delegate {
    
    
    @IBOutlet weak var sudNomer: UILabel!
    @IBOutlet weak var freestyleOcen: UIScrollView!
    
    var freestyleViv: Int!
    
    @IBOutlet weak var free1: UILabel!
    @IBOutlet weak var free2: UILabel!
    @IBOutlet weak var free3: UILabel!
    @IBOutlet weak var free4: UILabel!
    @IBOutlet weak var free5: UILabel!
    @IBOutlet weak var free6: UILabel!
    
    var ac1 = 0
    var ac2 = 0
    var ac3 = 0
    var ac4 = 0
    var ac5 = 0
    var ac6 = 0
    
    var num01 = 0
    var num03 = 0
    
    var pl03 = 0
    var pl01 = 0
    
    @IBOutlet weak var accyracy: UILabel!
    @IBOutlet weak var height: UILabel!
    @IBOutlet weak var numpuch: UILabel!
    @IBOutlet weak var angle: UILabel!
    @IBOutlet weak var sparring: UILabel!
    @IBOutlet weak var acrobatic: UILabel!
    @IBOutlet weak var basic: UILabel!
    
    @IBOutlet weak var loadVist: UIActivityIndicatorView!
    
    var radioButtonFreestyle1: RadioButtonFreestyle1?
    var radioButtonFreestyle2: RadioButtonFreestyle2?
    var radioButtonFreestyle3: RadioButtonFreestyle3?
    var radioButtonFreestyle4: RadioButtonFreestyle4?
    var radioButtonFreestyle5: RadioButtonFreestyle5?
    var radioButtonFreestyle6: RadioButtonFreestyle6?
    
    var Acd = 0.0
    
    @IBOutlet weak var height00: UIButton!
    @IBOutlet weak var height01: UIButton!
    @IBOutlet weak var height02: UIButton!
    @IBOutlet weak var height03: UIButton!
    @IBOutlet weak var height04: UIButton!
    @IBOutlet weak var height05: UIButton!
    @IBOutlet weak var height06: UIButton!
    @IBOutlet weak var height07: UIButton!
    @IBOutlet weak var height08: UIButton!
    @IBOutlet weak var height09: UIButton!
    @IBOutlet weak var height10: UIButton!
    
    @IBOutlet weak var numpuch00: UIButton!
    @IBOutlet weak var numpuch01: UIButton!
    @IBOutlet weak var numpuch02: UIButton!
    @IBOutlet weak var numpuch03: UIButton!
    @IBOutlet weak var numpuch04: UIButton!
    @IBOutlet weak var numpuch05: UIButton!
    @IBOutlet weak var numpuch06: UIButton!
    @IBOutlet weak var numpuch07: UIButton!
    @IBOutlet weak var numpuch08: UIButton!
    @IBOutlet weak var numpuch09: UIButton!
    @IBOutlet weak var numpuch10: UIButton!
    
    @IBOutlet weak var angle00: UIButton!
    @IBOutlet weak var angle01: UIButton!
    @IBOutlet weak var angle02: UIButton!
    @IBOutlet weak var angle03: UIButton!
    @IBOutlet weak var angle04: UIButton!
    @IBOutlet weak var angle05: UIButton!
    @IBOutlet weak var angle06: UIButton!
    @IBOutlet weak var angle07: UIButton!
    @IBOutlet weak var angle08: UIButton!
    @IBOutlet weak var angle09: UIButton!
    @IBOutlet weak var angle10: UIButton!
    
    @IBOutlet weak var sparring00: UIButton!
    @IBOutlet weak var sparring01: UIButton!
    @IBOutlet weak var sparring02: UIButton!
    @IBOutlet weak var sparring03: UIButton!
    @IBOutlet weak var sparring04: UIButton!
    @IBOutlet weak var sparring05: UIButton!
    @IBOutlet weak var sparring06: UIButton!
    @IBOutlet weak var sparring07: UIButton!
    @IBOutlet weak var sparring08: UIButton!
    @IBOutlet weak var sparring09: UIButton!
    @IBOutlet weak var sparring10: UIButton!
    
    @IBOutlet weak var acrobatic00: UIButton!
    @IBOutlet weak var acrobatic01: UIButton!
    @IBOutlet weak var acrobatic02: UIButton!
    @IBOutlet weak var acrobatic03: UIButton!
    @IBOutlet weak var acrobatic04: UIButton!
    @IBOutlet weak var acrobatic05: UIButton!
    @IBOutlet weak var acrobatic06: UIButton!
    @IBOutlet weak var acrobatic07: UIButton!
    @IBOutlet weak var acrobatic08: UIButton!
    @IBOutlet weak var acrobatic09: UIButton!
    @IBOutlet weak var acrobatic10: UIButton!
    
    @IBOutlet weak var basic10: UIButton!
    @IBOutlet weak var basic09: UIButton!
    @IBOutlet weak var basic08: UIButton!
    @IBOutlet weak var basic07: UIButton!
    @IBOutlet weak var basic06: UIButton!
    @IBOutlet weak var basic05: UIButton!
    @IBOutlet weak var basic04: UIButton!
    @IBOutlet weak var basic03: UIButton!
    @IBOutlet weak var basic02: UIButton!
    @IBOutlet weak var basic01: UIButton!
    @IBOutlet weak var basic00: UIButton!
    
    
    var idhost: String?
    var phumseName: String?
    var sudNum: Int?
    var kolSud: Int?
    var sys: Int!
    var kort: Int?
    
    var idvistuplenie: Int?
    var success: Int?
    var pokaz: Int?
    
    var URL_VISTUP: String?
    let URL_VISTUPLENIE2 = "/php_isap/vistup/vistuplenie.php"
    
    var URL_SUD: String?
    let URL_SUD2 = "/php_isap/sud/sudi.php"
    
    var URL_SUDGOT: String?
    let URL_SUDGOT2 = "/php_isap/sud/sudigotov.php"
    
    var gotov = 0
    
    func radioButton1SelectButton(selectedButton: UIButton?) {
        height.text = selectedButton?.currentTitle
        ac1 = Int(Double(selectedButton?.currentTitle ?? "0.0")!*10)
        printScoring()
    }
    
    func radioButton2SelectButton(selectedButton: UIButton?) {
        numpuch.text = selectedButton?.currentTitle
        ac2 = Int(Double(selectedButton?.currentTitle ?? "0.0")!*10)
        printScoring()
    }
    
    func radioButton3SelectButton(selectedButton: UIButton?) {
        angle.text = selectedButton?.currentTitle
        ac3 = Int(Double(selectedButton?.currentTitle ?? "0.0")!*10)
        printScoring()
    }
    
    func radioButton4SelectButton(selectedButton: UIButton?) {
        sparring.text = selectedButton?.currentTitle
        ac4 = Int(Double(selectedButton?.currentTitle ?? "0.0")!*10)
        printScoring()
    }
    
    func radioButton5SelectButton(selectedButton: UIButton?) {
        acrobatic.text = selectedButton?.currentTitle
        ac5 = Int(Double(selectedButton?.currentTitle ?? "0.0")!*10)
        printScoring()
    }
    
    func radioButton6SelectButton(selectedButton: UIButton?) {
        basic.text = selectedButton?.currentTitle
        ac6 = Int(Double(selectedButton?.currentTitle ?? "0.0")!*10)
        printScoring()
    }
    
    @objc func vistuplenieItem() {
        let url: URL = URL(string: self.URL_VISTUP ?? "localhost")!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
        
        let task = defaultSession.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("Failed to download data")
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    self.vistuplenieItem()
                })
            }else {
                self.parseJSONVistup(data!)
            }
        }
        task.resume()
    }
    
    func parseJSONVistup(_ data:Data) {
        var jsonResult = NSDictionary()
        do {
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
            let idvist = jsonResult["success"] as? String
            let kolVist = jsonResult["vistuplenie_pokaz"] as? String
            let phum = jsonResult["phumse"] as? String
            if (idvist != "") {
                self.idvistuplenie = Int (idvist!)!
                self.pokaz = Int (kolVist!)!
                self.phumseName = String (phum!)
            } else { self.idvistuplenie = 0 }
        } catch {
            print(error)
        }
        
        if (self.idvistuplenie != 0) {
            sudi()
        } else {
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                self.vistuplenieItem()
            })
        }
    }
    
        func sudi()  {
            self.URL_SUD = self.idhost! + self.URL_SUD2
            let requestURL = NSURL(string: URL_SUD!)
            //creating NSMutableURLRequest
            let request = NSMutableURLRequest(url: requestURL! as URL)
            //setting the method to post
            request.httpMethod = "POST"
            //creating the post parameter by concatenating the keys and values from text field
            let postParameters = "vistuplenie_idvistuplenie="+String(self.idvistuplenie!)+"&nomersud="+String (self.sudNum!)
            //adding the parameters to request body
            request.httpBody = postParameters.data(using: String.Encoding.utf8)
            var myJSON = NSDictionary()
            //creating a task to send the post request
            let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in
                do {
                    if (error != nil) {
                        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                            self.sudi()
                        })
                    } else {
                        myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                        self.success = (myJSON["success"] as! Int?)!
                        if(self.success! > 0) {
                            self.sudigotov()
                        } else {
                            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                                self.sudi()
                            })
                        }
                    }
                } catch {
                    print(error)
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                         self.sudi()
                     })
                }
            }
            //executing the task
            task.resume()
        }
        
        func sudigotov()  {
            self.URL_SUDGOT = self.idhost! + self.URL_SUDGOT2
            let requestURL = NSURL(string: URL_SUDGOT!)
            //creating NSMutableURLRequest
            let request = NSMutableURLRequest(url: requestURL! as URL)
            //setting the method to post
            request.httpMethod = "POST"
            //creating the post parameter by concatenating the keys and values from text field
            let postParameters = "vistuplenie_idvistuplenie=" + String (self.idvistuplenie!);
            //adding the parameters to request body
            request.httpBody = postParameters.data(using: String.Encoding.utf8)
            var myJSON = NSDictionary()
            //creating a task to send the post request
            let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in
                
                //parsing the response
                do {
                    //converting resonse to NSDictionary
                    if (error != nil) {
                        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                            self.sudigotov()
                        })
                    } else {
                    myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    }
                } catch {
                    print("Tut error")
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.sudigotov()
                    })
                }
                self.success = (myJSON["success"] as! Int?)!
                if (self.success != self.kolSud) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.sudigotov()
                    })
                } else {
                    DispatchQueue.main.async {
                        if (self.pokaz == 2 && self.sys == 5) {
    //                        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    //                        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "freestyleView") as! FreestyleViewController
    //                        nextViewController.idhost = self.idhost
    //                        nextViewController.sudNum = self.sudNum
    //                        nextViewController.kolSud = self.kolSud
    //                        nextViewController.sys = self.sys;
    //                        self.navigationController?.pushViewController(nextViewController, animated: true)
                        } else {
                            self.loadVist.stopAnimating()
                            self.loadVist.isHidden = true
                            self.freestyleOcen.isHidden = false
                            self.gotov = 1
                            self.sudNomer.text = "Судья № " + String (self.sudNum!)
                        }
                    }
                }
            }
            //executing the task
            task.resume()
        }
    

    func printScoring() {
        
        height.text = String(Double(ac1)/Double(10))
        numpuch.text = String(Double(ac2)/Double(10))
        angle.text = String(Double(ac3)/Double(10))
        sparring.text = String(Double(ac4)/Double(10))
        basic.text = String(Double(ac6)/Double(10))
        acrobatic.text = String(Double(ac5)/Double(10))
        Acd = (Double(ac1+ac2+ac3+ac4+ac5+ac6)/Double(10))
        if (Acd > 0 ) {
            accyracy.text = String(Double(ac1+ac2+ac3+ac4+ac5+ac6)/Double(10))
        } else {
            accyracy.text = "0.0"
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.setHidesBackButton(true, animated: true)
        
        freestyleOcen.isHidden = true
        printScoring()
        self.URL_VISTUP = self.idhost! + self.URL_VISTUPLENIE2
        self.loadVist.isHidden = false
        self.loadVist.startAnimating()
        
        switch freestyleViv {
        case 1:
            free1.text = "Ударные и защитные техники руками (в том числе с оружием)"
            free2.text = "Удары ногами в прыжке"
            free3.text = "Уддары ногами с вращением (180,360,540,720 и тд.)"
            free4.text = "Навыки владения оружием"
            free5.text = "Передвижение (выход,уход)"
            free6.text = "Акробатика"
            break
        case 2:
            break
        case 3:
            free1.text = "Бросковые техники"
            free2.text = "Разбивание предметов (доски и тп)"
            free3.text = "Сложные ударные техники ногами"
            free4.text = "Навыки владения оружием"
            free5.text = "Динамика, передвижение (выход,уход)"
            free6.text = "Акробатика"
            break
        default:
            break
        }
        
        radioButtonFreestyle1 = RadioButtonFreestyle1(buttons: height00, height01, height02, height03, height04, height05, height06, height07, height08, height09, height10)
        radioButtonFreestyle1!.delegate = self
        radioButtonFreestyle1!.shouldLetDeSelect = true
        
        radioButtonFreestyle2 = RadioButtonFreestyle2(buttons: numpuch00, numpuch01, numpuch02, numpuch03, numpuch04, numpuch05, numpuch06, numpuch07, numpuch08, numpuch09, numpuch10)
        radioButtonFreestyle2!.delegate = self
        radioButtonFreestyle2!.shouldLetDeSelect = true
        
        radioButtonFreestyle3 = RadioButtonFreestyle3(buttons: angle00, angle01, angle02, angle03, angle05, angle06, angle07, angle08, angle04, angle09, angle10)
        radioButtonFreestyle3!.delegate = self
        radioButtonFreestyle3!.shouldLetDeSelect = true
        
        radioButtonFreestyle4 = RadioButtonFreestyle4(buttons: sparring00, sparring01, sparring02, sparring03, sparring04, sparring05, sparring06, sparring07, sparring08, sparring09, sparring10)
        radioButtonFreestyle4!.delegate = self
        radioButtonFreestyle4!.shouldLetDeSelect = true
        
        radioButtonFreestyle5 = RadioButtonFreestyle5(buttons: acrobatic00, acrobatic01, acrobatic02, acrobatic03, acrobatic04, acrobatic05, acrobatic06, acrobatic07, acrobatic08, acrobatic09, acrobatic10)
        radioButtonFreestyle5!.delegate = self
        radioButtonFreestyle5!.shouldLetDeSelect = true
        
        radioButtonFreestyle6 = RadioButtonFreestyle6(buttons: basic10, basic09, basic08, basic07, basic06, basic05, basic04, basic03, basic02, basic01, basic00)
        radioButtonFreestyle6!.delegate = self
        radioButtonFreestyle6!.shouldLetDeSelect = true
        
        vistuplenieItem()
    }
    
    override func prepare (for segue: UIStoryboardSegue, sender: Any?) {
        let frestylePresentationController: HapkidoFreestylePresController = segue.destination as! HapkidoFreestylePresController
        frestylePresentationController.idhost = self.idhost
        frestylePresentationController.sudNum = self.sudNum
        frestylePresentationController.idvistuplenie = self.idvistuplenie!
        frestylePresentationController.Acd = self.Acd
        frestylePresentationController.num01 = self.num01
        frestylePresentationController.num03 = self.num03
        frestylePresentationController.kolSud = self.kolSud
        frestylePresentationController.pokaz = self.pokaz
        frestylePresentationController.sys = self.sys
        frestylePresentationController.kort = self.kort
    }
    
}

